import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 关闭进度条圈圈
NProgress.configure({
  showSpinner: false
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登录'
      }
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: {
        title: '家庭档案'
      }
    },
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/Home/index.vue'),
          meta: {
            title: '首页'
          }
        },
        {
          path: '/article',
          component: () => import('@/views/Article/index.vue'),
          meta: {
            title: '健康百科'
          }
        },
        {
          path: '/notify',
          component: () => import('@/views/Notify/index.vue'),
          meta: {
            title: '消息中心'
          }
        },
        {
          path: '/user',
          component: () => import('@/views/User/index.vue'),
          meta: {
            title: '我的'
          }
        }
      ]
    }
  ]
})
// vue3全局后置守卫升级，即使路由重定向也可以经过路由后置守卫,不需要手动关闭

router.beforeEach((to) => {
  // 开启进度条
  NProgress.start()
  // 没有token && 不在白名单
  const userStore = useUserStore()
  // 白名单
  const whiteList = ['/login']
  if (!userStore.user?.token && !whiteList.includes(to.path)) return '/login'
  // 函数不写返回值，返回值默认是undefined
  // return true
})
// document.title设置页面标题 - 通过路由元信息router的meta
// xx-优医问诊
router.afterEach((to) => {
  // 关闭进度条
  NProgress.done()
  document.title = `${to.meta.title || ''}-优医问诊`
})
export default router
